package com.quaidi.smartlocker.controller;

import com.quaidi.smartlocker.annotation.RequireRole;
import com.quaidi.smartlocker.common.Result;
import com.quaidi.smartlocker.dto.PackageDepositRequest;
import com.quaidi.smartlocker.dto.PackagePickupRequest;
import com.quaidi.smartlocker.entity.ExpressPackage;
import com.quaidi.smartlocker.enums.UserRole;
import com.quaidi.smartlocker.service.ExpressPackageService;
import com.quaidi.smartlocker.service.OperationLogService;
// import io.swagger.annotations.Api;
// import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 快递包裹存取Controller
 * 
 * @author QuaiDi
 * @since 2025-08-26
 */
// @Api(tags = "快递包裹存取")
@RestController
@RequestMapping("/api/packages")
public class ExpressPackageController {

    @Autowired
    private ExpressPackageService expressPackageService;

    @Autowired
    private OperationLogService operationLogService;

    /**
     * 存放快递包裹
     */
    // @ApiOperation("存放快递包裹")
    @PostMapping("/deposit")
    public Result<ExpressPackage> depositPackage(@Valid @RequestBody PackageDepositRequest request,
                                                 HttpServletRequest httpRequest) {
        try {
            ExpressPackage expressPackage = expressPackageService.depositPackage(request);
            
            // 记录操作日志
            operationLogService.recordLog(
                "DEPOSIT", 
                "SYSTEM", 
                expressPackage.getId(), 
                "PACKAGE",
                "存放快递包裹：" + request.getTrackingNumber(),
                "SUCCESS",
                getClientIp(httpRequest)
            );
            
            return Result.success("快递存放成功", expressPackage);
        } catch (Exception e) {
            // 记录失败日志
            operationLogService.recordLog(
                "DEPOSIT", 
                "SYSTEM", 
                null, 
                "PACKAGE",
                "存放快递包裹失败：" + request.getTrackingNumber() + "，原因：" + e.getMessage(),
                "FAILED",
                getClientIp(httpRequest)
            );
            return Result.error(e.getMessage());
        }
    }

    /**
     * 取件
     */
    // @ApiOperation("取件")
    @PostMapping("/pickup")
    public Result<ExpressPackage> pickupPackage(@Valid @RequestBody PackagePickupRequest request,
                                                HttpServletRequest httpRequest) {
        try {
            ExpressPackage expressPackage = expressPackageService.pickupPackage(request);
            
            // 记录操作日志
            operationLogService.recordLog(
                "PICKUP", 
                request.getRecipientPhone(), 
                expressPackage.getId(), 
                "PACKAGE",
                "取件成功：" + expressPackage.getTrackingNumber(),
                "SUCCESS",
                getClientIp(httpRequest)
            );
            
            return Result.success("取件成功", expressPackage);
        } catch (Exception e) {
            // 记录失败日志
            operationLogService.recordLog(
                "PICKUP", 
                request.getRecipientPhone(), 
                null, 
                "PACKAGE",
                "取件失败，取件码：" + request.getPickupCode() + "，原因：" + e.getMessage(),
                "FAILED",
                getClientIp(httpRequest)
            );
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据取件码查询包裹信息
     */
    // @ApiOperation("根据取件码查询包裹信息")
    @GetMapping("/query")
    public Result<ExpressPackage> queryPackage(@RequestParam String pickupCode, 
                                              @RequestParam String recipientPhone) {
        try {
            ExpressPackage expressPackage = expressPackageService.getByPickupCodeAndPhone(pickupCode, recipientPhone);
            if (expressPackage == null) {
                return Result.error("未找到相关包裹信息，请检查取件码和电话号码是否正确");
            }
            return Result.success(expressPackage);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 仅根据取件码查询包裹信息（用于调试和管理）
     */
    // @ApiOperation("仅根据取件码查询包裹信息")
    @RequireRole(UserRole.ADMIN)
    @GetMapping("/query-by-code")
    public Result<ExpressPackage> queryByPickupCode(@RequestParam String pickupCode) {
        try {
            ExpressPackage expressPackage = expressPackageService.getByPickupCode(pickupCode);
            if (expressPackage == null) {
                return Result.error("未找到取件码为 " + pickupCode + " 的包裹");
            }
            return Result.success(expressPackage);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据快递单号查询包裹信息
     */
    // @ApiOperation("根据快递单号查询包裹信息")
    @GetMapping("/track/{trackingNumber}")
    public Result<ExpressPackage> trackPackage(@PathVariable String trackingNumber) {
        try {
            ExpressPackage expressPackage = expressPackageService.getByTrackingNumber(trackingNumber);
            if (expressPackage == null) {
                return Result.error("未找到相关包裹信息");
            }
            return Result.success(expressPackage);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}